<template>
  <view class="culture-page">
    <!-- 分类选择器 -->
    <view class="category-selector">
      <scroll-view class="category-scroll" scroll-x="true" show-scrollbar="false">
        <view class="category-list">
          <view
            class="category-item"
            :class="{ active: selectedCategoryId === 0 }"
            @click="selectCategory(0)"
          >
            <text>全部</text>
          </view>
          <view
            v-for="category in categoryList"
            :key="category.id"
            class="category-item"
            :class="{ active: selectedCategoryId === category.id }"
            @click="selectCategory(category.id)"
          >
            <text>{{ category.name }}</text>
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 文章列表 -->
    <view class="article-list">
      <view
        v-for="(article, index) in articleList"
        :key="article.id"
        class="article-item"
        @click="viewArticleDetail(article)"
      >
        <!-- 文章封面 -->
        <view v-if="getArticleCover(article.content)" class="article-cover">
          <image :src="getArticleCover(article.content)" mode="aspectFill" />
        </view>

        <!-- 文章内容 -->
        <view class="article-content">
          <view class="article-title">{{ article.title }}</view>
          <view class="article-excerpt">{{ getContentExcerpt(article.content) }}</view>
          <view class="article-meta">
            <view class="meta-left">
              <text class="author">{{ article.author }}</text>
              <text class="publish-time">{{ formatTime(article.createTime) }}</text>
            </view>
            <!-- <view class="meta-right">
              <text class="view-count">{{ article.viewCount }}阅读</text>
            </view> -->
          </view>
        </view>
      </view>
    </view>

    <!-- 加载更多 -->
    <view v-if="hasMore" class="load-more">
      <view class="load-more-btn" :class="{ loading: isLoading }" @click="loadMore">
        <text v-if="!isLoading">加载更多</text>
        <text v-else>加载中...</text>
      </view>
    </view>

    <!-- 空状态 -->
    <view v-if="articleList.length === 0 && !isLoading" class="empty-state">
      <image class="empty-icon" src="/static/icons/empty-data.png" mode="aspectFit" />
      <text class="empty-title">暂无文化内容</text>
      <text class="empty-desc">当前分类下暂无相关内容，请切换其他分类查看</text>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import CultureAPI, { type CultureContentItem, type CultureCategoryItem } from "@/api/culture";

// 文章列表数据
const articleList = ref<CultureContentItem[]>([]);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const hasMore = ref(true);
const isLoading = ref(false);

// 分类相关数据
const categoryList = ref<CultureCategoryItem[]>([]);
const selectedCategoryId = ref(0);

// 获取分类列表
const getCategoryList = async () => {
  try {
    const response = await CultureAPI.getCultureCategoryList({
      pageNum: "1",
      pageSize: "50", // 获取所有分类
    });

    const { list } = response;
    categoryList.value = list.filter((category) => category.status === 1); // 只显示启用的分类
  } catch (error) {
    console.error("获取分类列表失败:", error);
  }
};

// 选择分类
const selectCategory = (categoryId: number) => {
  selectedCategoryId.value = categoryId;
  currentPage.value = 1;
  getArticleList();
};

// 获取文章列表
const getArticleList = async (isLoadMore = false) => {
  if (isLoading.value) return;

  isLoading.value = true;
  try {
    const params: {
      pageNum: string;
      pageSize: string;
      categoryId?: string;
    } = {
      pageNum: currentPage.value.toString(),
      pageSize: pageSize.value.toString(),
    };

    // 如果选择了特定分类，添加分类ID参数
    if (selectedCategoryId.value > 0) {
      params.categoryId = selectedCategoryId.value.toString();
    }

    const response = await CultureAPI.getCultureContentList(params);

    // request工具已经处理了响应结构，直接使用data
    const { list, total: totalCount } = response;

    if (isLoadMore) {
      articleList.value.push(...list);
    } else {
      articleList.value = list;
    }

    total.value = totalCount;
    hasMore.value = articleList.value.length < totalCount;
  } catch (error) {
    console.error("获取文章列表失败:", error);
    uni.showToast({
      title: "获取数据失败",
      icon: "none",
    });
  } finally {
    isLoading.value = false;
  }
};

// 加载更多
const loadMore = () => {
  if (hasMore.value && !isLoading.value) {
    currentPage.value++;
    getArticleList(true);
  }
};

// 获取内容摘要
const getContentExcerpt = (content: string) => {
  if (!content) return "";
  // 移除HTML标签，获取纯文本
  const text = content.replace(/<[^>]+>/g, "");
  return text.length > 100 ? text.substring(0, 100) + "..." : text;
};

// 获取文章封面图
const getArticleCover = (content: string) => {
  if (!content) return "";
  // 从内容中提取第一张图片作为封面
  const imgMatch = content.match(/<img[^>]+src="([^"]+)"/);
  return imgMatch ? imgMatch[1] : "";
};

// 格式化时间
const formatTime = (timeStr: string | undefined) => {
  if (!timeStr) return "";
  const date = new Date(timeStr);
  const now = new Date();
  const diff = now.getTime() - date.getTime();

  const days = Math.floor(diff / (1000 * 60 * 60 * 24));
  const hours = Math.floor(diff / (1000 * 60 * 60));
  const minutes = Math.floor(diff / (1000 * 60));

  if (days > 0) {
    return `${days}天前`;
  } else if (hours > 0) {
    return `${hours}小时前`;
  } else if (minutes > 0) {
    return `${minutes}分钟前`;
  } else {
    return "刚刚";
  }
};

// 查看文章详情
const viewArticleDetail = (article: CultureContentItem) => {
  uni.navigateTo({
    url: `/pages/work/culture/detail?id=${article.id}`,
  });
};

// 页面加载时获取数据
onMounted(() => {
  getCategoryList();
  getArticleList();
});
</script>

<style lang="scss">
.culture-page {
  min-height: 100vh;
  background-color: #f8f8f8;
  padding-bottom: 30rpx;
}

.category-selector {
  padding: 20rpx 0 10rpx 0;
  background: #fff;
  border-radius: 20rpx;
  margin: 0 20rpx 10rpx 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(102, 126, 234, 0.08);
}

.category-scroll {
  white-space: nowrap;
  overflow-x: auto;
  -webkit-overflow-scrolling: touch;
}

.category-list {
  display: flex;
  align-items: center;
  gap: 18rpx; // 标签间距
  padding: 0 10rpx;
}

.category-item {
  min-width: 120rpx;
  padding: 18rpx 38rpx;
  border-radius: 32rpx;
  background-color: #f4f6fa;
  color: #333;
  font-size: 28rpx;
  font-weight: 500;
  text-align: center;
  transition: all 0.2s;
  box-shadow: 0 2rpx 8rpx rgba(102, 126, 234, 0.04);

  &.active {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: #fff;
    font-weight: bold;
    box-shadow: 0 4rpx 16rpx rgba(102, 126, 234, 0.18);
    border: none;
  }

  &:active {
    transform: scale(0.97);
  }
}

.article-list {
  padding: 20rpx;
}

.article-item {
  background-color: #fff;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  padding: 30rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
  transition: transform 0.2s ease;

  &:active {
    transform: scale(0.98);
  }

  .article-cover {
    width: 100%;
    height: 320rpx;
    border-radius: 12rpx;
    overflow: hidden;
    margin-bottom: 20rpx;

    image {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }

  .article-content {
    flex: 1;

    .article-title {
      font-size: 32rpx;
      font-weight: 600;
      color: #333;
      margin-bottom: 16rpx;
      line-height: 1.4;
      display: -webkit-box;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 2;
      overflow: hidden;
    }

    .article-excerpt {
      font-size: 28rpx;
      color: #666;
      line-height: 1.5;
      margin-bottom: 20rpx;
      display: -webkit-box;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 3;
      overflow: hidden;
    }

    .article-meta {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-size: 24rpx;
      color: #999;

      .meta-left {
        display: flex;
        align-items: center;

        .author {
          margin-right: 20rpx;
          color: #1989fa;
        }

        .publish-time {
          color: #999;
        }
      }

      .meta-right {
        .view-count {
          display: flex;
          align-items: center;

          &:before {
            content: "";
            display: inline-block;
            width: 24rpx;
            height: 24rpx;
            background: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="%23999"><path d="M12 4.5C7 4.5 2.73 7.61 1 12c1.73 4.39 6 7.5 11 7.5s9.27-3.11 11-7.5c-1.73-4.39-6-7.5-11-7.5zM12 17c-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5-2.24 5-5 5zm0-8c-1.66 0-3 1.34-3 3s1.34 3 3 3 3-1.34 3-3-1.34-3-3-3z"/></svg>');
            background-size: cover;
            margin-right: 6rpx;
          }
        }
      }
    }
  }
}

.load-more {
  text-align: center;
  padding: 40rpx 20rpx;

  .load-more-btn {
    display: inline-block;
    padding: 20rpx 40rpx;
    background-color: #fff;
    border-radius: 30rpx;
    font-size: 28rpx;
    color: #666;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
    transition: all 0.3s ease;

    &:active {
      transform: scale(0.95);
    }

    &.loading {
      opacity: 0.6;
    }
  }
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 160rpx 40rpx;

  .empty-icon {
    width: 240rpx;
    height: 240rpx;
    margin-bottom: 40rpx;
    opacity: 0.8;
  }

  .empty-title {
    font-size: 32rpx;
    color: #666;
    font-weight: 500;
    margin-bottom: 16rpx;
  }

  .empty-desc {
    font-size: 28rpx;
    color: #999;
    text-align: center;
    line-height: 1.5;
  }
}
</style>
